package com.cloudcc.boot.IAMService;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.cloudcc.boot.core.CCObject;
import com.cloudcc.boot.core.CCService;
import com.cloudcc.boot.core.ServiceResult;
import io.swagger.annotations.ApiOperation;
//import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.cloudcc.boot.core.CCService.userInfo;

@Controller
@RequestMapping(value = "/api")
@Slf4j
public class IDMClient {
    @Value("${system.IAM_APP_KEY}")
    private String IAM_APP_KEY; // 应用ID
    @Value("${system.IAM_APP_SECRET}")
    private String IAM_APP_SECRET; // 密钥
    @Value("${system.IAM_BASE_URL}")
    private String IAM_BASE_URL;//接口地址
    @Value("${system.profileID}")
    private String profileID;//临时简档ID
    @Value("${system.roleID}")
    private String roleID;//临时简档ID

    @ResponseBody
    @RequestMapping(value = "/getIAMCusterner", produces = "text/html;charset=UTF-8")
    @ApiOperation(value = "")
    public String getIAMCusterner(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CCService cs = new CCService(userInfo);
        JSONObject returnJson = new JSONObject();
        CCObject interfacerecordObj = new CCObject("interfacerecord");//接口同步记录-调用用户增量接口/account/list
        CCObject interfacecallbackObj = new CCObject("interfacerecord");//接口同步记录-调用用户回调接口/account/callback
        try {
            String date = request.getParameter("date") == null ? "" : request.getParameter("date").toString();//传入日期（昨天）
            // 获取JWT Token
            String token = getJwtToken(IAM_APP_KEY, IAM_APP_SECRET);
            log.info("token:" + token);
            String startTime = getStartTime(date);
            log.info("startTime:" + startTime);
            String url = IAM_BASE_URL + "/account/list";
            JSONObject obj = new JSONObject();
            obj.put("page", "1");
            obj.put("size", "100");
            if (StringUtils.isNotBlank(startTime)) {
                obj.put("startTime", startTime);
            }
            log.info("调用用户增量接口/account/list------入参param:" + obj);
            // 调用account/list接口
            String result = callAccountList(url, "Authorization", token, obj.toString());
//            String result = callAccountList1(token, 1, 10, startTime);
//            String result = "{\"code\":\"0\",\"timestamp\":\"1744940955144\",\"data\":{\"total\":\"2840\",\"size\":2,\"page\":1,\"list\":[{\"idt_user__mobile\":\"18862282765\",\"app_account__id\":\"\",\"request_log__id\":\"2193321248379915661\",\"jobs\":[],\"idt_user__user_uid\":\"admin@cloudcc.com\",\"idt_user__user_name\":\"王晓婷\",\"app_account__account_uuid\":\"\",\"request_log__action_desc\":\"管理员操作-修改主帐号\",\"idt_user__guid\":\"2192577166770719751\",\"app_account__account_no\":\"\",\"idt_user__email\":\"1300584390@qq.com\",\"request_log__action_flag\":1,\"idt_user__identity_code\":\"320581199207230120\",\"app_account__status\":\"\",\"useTypes\":[],\"idt_user__status\":1,\"orgs\":[{\"idt_org__org_code\":\"01422901\"}],\"app_account__account_name\":\"\",\"idt_user__gender\":1}]},\"msg\":\"操作成功\"}";
            log.info("调用用户增量接口/account/list------返回result:" + result);

            interfacerecordObj.put("url", url);//url
            interfacerecordObj.put("crcs", obj.toString());//传入参数
            interfacerecordObj.put("fhcs", result);//返回参数
            interfacerecordObj.put("zxzt", "处理成功");//执行状态

            // 解析返回数据并调用回调接口
            JSONObject resultJson = JSONObject.parseObject(result);
            String code = resultJson.getString("code");
            String msg = resultJson.getString("msg");
            JSONObject data = resultJson.getJSONObject("data");
            JSONArray userList = data.getJSONArray("list");

            List<String> idsList = new ArrayList<>();
            List<JSONObject> errorsList = new ArrayList<>();

            for (int i = 0; i < userList.size(); i++) {
                JSONObject user = userList.getJSONObject(i);

                String logid = user.get("request_log__id")==null?"":user.get("request_log__id").toString();
                String loginName = user.get("idt_user__user_uid")==null?"":user.get("idt_user__user_uid").toString();
                String name = user.get("idt_user__user_name")==null?"":user.get("idt_user__user_name").toString();
                String email = user.get("idt_user__email")==null?"":user.get("idt_user__email").toString();
                if (StringUtils.isBlank(email)){
                    email = "test@interface.com";
                }
                String gender = user.get("idt_user__gender")==null?"":user.get("idt_user__gender").toString();
                String mobile = user.get("idt_user__mobile")==null?"":user.get("idt_user__mobile").toString();
                String status = user.get("idt_user__status")==null?"":user.get("idt_user__status").toString();
                String no = user.get("idt_user__work_no")==null?"":user.get("idt_user__work_no").toString();
                String identitycode = user.get("idt_user__identity_code")==null?"":user.get("idt_user__identity_code").toString();
                String guid = user.get("idt_user__guid")==null?"":user.get("idt_user__guid").toString();

                CCObject CCOuser = new CCObject("ccuser");
                if ("0".equals(gender)) {//性别 - 男
                    CCOuser.put("gender", "男");
                }
                if ("1".equals(gender)) {//性别 - 女
                    CCOuser.put("gender", "女");
                }
                CCOuser.put("mobile", mobile);//手机号码
                CCOuser.put("employeenum", no);//工号
                CCOuser.put("identitycode", identitycode);//证件编号
                CCOuser.put("guid", guid);//guid

                List<CCObject> user_List = cs.cquery("ccuser", "loginname='" + loginName + "'");
                if (user_List.size() > 0) {
                    idsList.add(logid);

                    String userId = user_List.get(0).get("id").toString();
                    CCOuser.put("id", userId);
                    if ("0".equals(status)) {//状态 - 停用
                        CCOuser.put("isusing", "0");
                    }
                    cs.update(CCOuser);
                } else {
                    // 调用createUser方法创建用户
                    ServiceResult return_value = cs.createUser(loginName, name, email, profileID, roleID, "CRRC@crm2025");
                    log.info("======================用户"+loginName+"插入return_value:"+return_value);
                    JSONObject returnjsonObject = JSON.parseObject(JSON.toJSONString(return_value));
                    String result_str = returnjsonObject.getString("result");
                    String returnInfo_str = returnjsonObject.getString("returnInfo");


                    if ("true".equals(result_str)) {
                        idsList.add(logid);
                        List<CCObject> newuser_List = cs.cquery("ccuser", "loginname='" + loginName + "'");
                        if (newuser_List.size() > 0) {
                            String newuserId = newuser_List.get(0).get("id").toString();
                            CCOuser.put("id", newuserId);
                        }
                        CCOuser.put("isusing", "0");
                        cs.update(CCOuser);
                        log.info("======================用户"+loginName+"插入后update数据:"+CCOuser);
                    }else{
                        JSONObject errobj = new JSONObject();
                        errobj.put("msg", returnInfo_str);
                        errobj.put("id", logid);
                        errorsList.add(errobj);

                    }
                }
            }

            // 构造回调接口的请求体
            JSONObject callbackObj = new JSONObject();
            callbackObj.put("ids", String.join(",", idsList));
            if (!errorsList.isEmpty()) {
                callbackObj.put("errors", errorsList);
            }
            log.info("接口同步记录-调用用户回调接口/account/callback------入参param:" + callbackObj);

            interfacecallbackObj.put("url", "http://***/ccdomaingateway/apisvc/openApi/common");//url
            interfacecallbackObj.put("crcs", "serviceName:createUser");//传入参数
            interfacecallbackObj.put("fhcs", callbackObj.toString());//返回参数
            interfacecallbackObj.put("zxzt", "处理成功");//执行状态

//            // 调用account/callback接口
//            String callbackUrl = IAM_BASE_URL + "/account/callback";
//            String callbackResult = callAccountCallback(callbackUrl, "Authorization", token, callbackObj.toString());
//            log.info("callbackResult: " + callbackResult);

            log.info("接口同步记录-调用用户回调接口/account/callback------返回callbackResult:");

            returnJson.put("result", "true");
            returnJson.put("returnInfo", "操作成功---");
            returnJson.put("returnCode", "1");

        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("result", "false");
            returnJson.put("returnInfo", e.getMessage());
            returnJson.put("returnCode", "-1");
            log.info("报错信息：" + e.toString());
        } finally {
//            interfacerecordObj.put("fhcs", returnJson.toString());//返回参数
            //写入数据 newObj
            ServiceResult sr = cs.insert(interfacerecordObj);
            ServiceResult sr_user = cs.insert(interfacecallbackObj);
        }
        return returnJson.toString();
    }

    /**
     * 调用IDM查询组织数据接口，并更新CRM系统【IDM组织】表数据
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getIAM_Org", produces = "text/html;charset=UTF-8")
    @ApiOperation(value = "")
    public String getIAM_Org(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CCService cs = new CCService(userInfo);
        JSONObject returnJson = new JSONObject();
        CCObject interfacerecordObj = new CCObject("interfacerecord");//接口同步记录-调用查询组织接口/org/list
        try {
            String date = request.getParameter("date") == null ? "" : request.getParameter("date").toString();//传入日期（昨天）
            // 获取JWT Token
            String token = getJwtToken(IAM_APP_KEY, IAM_APP_SECRET);
            log.info("token:" + token);
            String startTime = getStartTime(date);
            log.info("startTime:" + startTime);
            String url = IAM_BASE_URL + "/org/list";
            JSONObject obj = new JSONObject();
            obj.put("page", "1");
            obj.put("size", "1000");
            if (StringUtils.isNotBlank(startTime)) {
                obj.put("startTime", startTime);
            }
            log.info("调用查询组织数据接口/org/list------入参param:" + obj);
            // 调用account/list接口
            String result = callAccountList(url, "Authorization", token, obj.toString());
//            String result = callAccountList1(token, 1, 10, startTime);
//            String result = "{\"code\":\"0\",\"timestamp\":\"1745290234936\",\"data\":{\"total\":\"304\",\"size\":100,\"page\":1,\"list\":[{\"request_log__id\":\"2195494415932346425\",\"idt_org__name\":\"中车山东机车车辆有限公司\",\"request_log__action_desc\":\"管理员操作-重新执行组织供应策略\",\"idt_org__org_code\":\"0142\",\"idt_org_director_link__user_id\":null,\"request_log__action_flag\":0,\"idt_org__status\":1,\"idt_org__grading_leader\":null,\"orgTypes\":[{\"idt_org_type__name\":\"单位\"}],\"idt_org_type__name\":\"中车山东机车车辆有限公司\",\"idt_org__org_co\":null,\"idt_org__id\":\"2192577162475752842\",\"orgDirector\":[],\"idt_org__sup_org_code\":\"\"}]},\"msg\":\"操作成功\"}";
//            log.info("调用查询组织数据接口/org/list------返回result:" + result);

            interfacerecordObj.put("url", url);//url
            interfacerecordObj.put("crcs", obj.toString());//传入参数
            interfacerecordObj.put("fhcs", result);//返回参数
            interfacerecordObj.put("zxzt", "处理成功");//执行状态

            // 解析返回数据并调用回调接口
            JSONObject resultJson = JSONObject.parseObject(result);
            String code = resultJson.getString("code");
            String msg = resultJson.getString("msg");
            JSONObject data = resultJson.getJSONObject("data");
            JSONArray userList = data.getJSONArray("list");

            List<String> idsList = new ArrayList<>();
            List<JSONObject> errorsList = new ArrayList<>();

            for (int i = 0; i < userList.size(); i++) {
                JSONObject user = userList.getJSONObject(i);
                log.info("当前待读取user------------------"+user);

                String log__id = user.get("request_log__id") == null || "null".equals(user.get("request_log__id")) ? "" : user.get("request_log__id").toString();
                String name = user.get("idt_org__name") == null || "null".equals(user.get("idt_org__name")) ? "" : user.get("idt_org__name").toString();
                String org_code = user.get("idt_org__org_code") == null || "null".equals(user.get("idt_org__org_code")) ? "" : user.get("idt_org__org_code").toString();
                String user_id = user.get("idt_org_director_link__user_id") == null || "null".equals(user.get("idt_org_director_link__user_id")) ? "" : user.get("idt_org_director_link__user_id").toString();
                String status = user.get("idt_org__status") == null || "null".equals(user.get("idt_org__status")) ? "" : user.get("idt_org__status").toString();
                String grading_leader = user.get("idt_org__grading_leader") == null || "null".equals(user.get("idt_org__grading_leader")) ? "" : user.get("idt_org__grading_leader").toString();
                String idt_org_type__name = user.get("idt_org_type__name") == null || "null".equals(user.get("idt_org_type__name")) ? "" : user.get("idt_org_type__name").toString();
                String org_co = user.get("idt_org__org_co") == null || "null".equals(user.get("idt_org__org_co")) ? "" : user.get("idt_org__org_co").toString();
                String org_id = user.get("idt_org__id") == null || "null".equals(user.get("idt_org__id")) ? "" : user.get("idt_org__id").toString();
                String sup_org_code = user.get("idt_org__sup_org_code") == null || "null".equals(user.get("idt_org__sup_org_code")) ? "" : user.get("idt_org__sup_org_code").toString();

                CCObject orguser = new CCObject("idm_org");//IDM组织
                orguser.put("name", name);//组织名称
                orguser.put("org_code", org_code);//组织编码
                orguser.put("user_id", user_id);//组织主管
                if ("0".equals(status)) {//性别 - 男
                    orguser.put("zt", "停用");
                }else if ("1".equals(status)) {//性别 - 男
                    orguser.put("zt", "正常");
                }else if ("-1".equals(status)) {//性别 - 男
                    orguser.put("zt", "删除");
                }
                orguser.put("grading_leader", grading_leader);//分管领导
                orguser.put("idt_org_type__name", idt_org_type__name);//组织类型
                orguser.put("org_co", org_co);//所属公司
                orguser.put("org_id", org_id);//组织id
                orguser.put("sup_org_code", sup_org_code);//上级组织编码

                List<CCObject> org_List = cs.cquery("idm_org", "org_id='" + org_id + "'");
                if (org_List.size() > 0) {
                    String newuserId = org_List.get(0).get("id").toString();
                    orguser.put("id", newuserId);
                    log.info("调用查询组织数据接口/org/list------更新--obj:"+orguser);
                    cs.update(orguser);
                }else {
                    log.info("调用查询组织数据接口/org/list------新增--obj:"+orguser);
                    cs.insert(orguser);
                }

            }

            returnJson.put("result", "true");
            returnJson.put("returnInfo", "操作成功---");
            returnJson.put("returnCode", "1");

        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("result", "false");
            returnJson.put("returnInfo", e.getMessage());
            returnJson.put("returnCode", "-1");
            log.info("报错信息：" + e.toString());
        } finally {
//            interfacerecordObj.put("fhcs", returnJson.toString());//返回参数
            //写入数据 newObj
            ServiceResult sr = cs.insert(interfacerecordObj);
        }
        return returnJson.toString();
    }

    public static String getJwtToken(String appKey, String appSecret) {
        String token = JWT.create()
                .withIssuer(appKey)
                .withIssuedAt(new Date())
                .withJWTId(IdUtil.fastSimpleUUID())
                .sign(Algorithm.HMAC256(appSecret));
        return "Bearer " + token;
        /*String secret = String.join(":", appKey, appSecret);
        byte[] originalBytes = secret.getBytes(CharsetUtil.CHARSET_UTF_8);
        String encodedString = Base64.getEncoder().encodeToString(originalBytes);
        String basicToken = String.join(" ", "Basic", encodedString);
//        System.out.println("basic=================="+basicToken);
        return basicToken;*/
    }

    /**
     * 获取JWT Token
     *
     * @param dateString yyyy-mm-dd日期
     * @return 生成的JWT Token
     */
    public static String getStartTime(String dateString) {
        // 创建DateTimeFormatter，指定日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析字符串为LocalDate对象
        LocalDate date = LocalDate.parse(dateString, formatter);
        // 转换为毫秒表示的时间戳（自1970-01-01 00:00:00 UTC以来的毫秒数）
        long timestampMillis = date.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
        // 如果需要秒数，可以将毫秒转换为秒
//        long timestampSeconds = timestampMillis / 1000;
        return timestampMillis + "";
    }

    public String callAccountList(String path, String tokenname, String token, String param) {
        String result = "";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(path);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader(tokenname, token);
            httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = "发送 POST 请求出现异常！" + e.getMessage();
        }
        return result;
    }

    /**
     * 调用account/list接口
     *
     * @param token     JWT Token
     * @param page      页码
     * @param size      每页条数
     * @param startTime 开始时间（可选）
     * @return 返回的JSON字符串
     * @throws Exception 如果发生异常
     */
    public String callAccountList1(String token, int page, int size, String startTime) throws Exception {
        String url = IAM_BASE_URL + "/account/list";
        // 创建 RequestConfig 并设置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Authorization", token);
        JSONObject obj = new JSONObject();
        obj.put("page", page);
        obj.put("size", size);
        if (StringUtils.isNotBlank(startTime)) {
            obj.put("startTime", startTime);
        }
        httpPost.setEntity(new StringEntity(JSONObject.toJSONString(obj), "UTF-8"));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            return EntityUtils.toString(responseEntity, "UTF-8");
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            // 获取JWT Token
            String token = getJwtToken("bdf861d48f034d88", "16776482cc4c444ea711673905965114");
            System.out.println("token:" + token);
            String startTime = getStartTime("2025-04-20");
            System.out.println("startTime：" + startTime);
//            String url = BASE_URL + "/account/list";
            String url = "";
            System.out.println("url==============" + url);
            JSONObject obj = new JSONObject();
            obj.put("page", "1");
            obj.put("size", "10");
            if (StringUtils.isNotBlank(startTime)) {
                obj.put("startTime", startTime);
            }
            // 调用account/list接口
//             String response = callAccountList(url,"Authorization", token, obj.toString());
//            String response = callAccountList1(token, 1, 10, startTime);
//            System.out.println("Response: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}